from django.contrib.auth.hashers import make_password
from django.core.management.base import BaseCommand
from django.conf import settings
from pathlib import Path
import yaml
from datetime import datetime

from ctbloge.apps.accounts.models import UserProfile
from ctbloge.apps.cms.models import Article, Category, Tag, Topic, ArticleImage
from django.utils.text import slugify
import html2text
import re
import yaml
from datetime import datetime
from markdown import markdown


class Command(BaseCommand):
    help = 'Import markdown files from directory into articles'

    def handle(self, *args, **options):
        md_dir = Path(settings.MEDIA_ROOT) / 'cms/md'

        for md_file in md_dir.glob('*.md'):
            with open(md_file, 'r', encoding='utf-8') as f:
                content = f.read()

            # 解析YAML Frontmatter
            frontmatter= self.parse_md_content(content)

            try:
                # 转换内容为HTML
                html_content = markdown(frontmatter['raw_content'])
                # 处理作者信息
                author_name = frontmatter.get('author_name')
                author_email = frontmatter.get('author_email')

                author, _ = UserProfile.objects.update_or_create(
                    email=author_email,
                    defaults={
                        'username': author_name,
                        'password': make_password('admin123'),
                    }
                )
                frontmatter['author'] = author
                #处理分类信息
                if frontmatter.get('category'):
                    category_name = frontmatter['_category_name']
                    category_slug = frontmatter['_category_slug']
                    category_description = frontmatter['_category_description']
                    category, _ = Category.objects.update_or_create(
                        name=category_name,
                        slug=category_slug,
                        defaults={
                            'description': category_description,
                        }
                    )
                    frontmatter['category'] = category
                # 处理专题信息
                if frontmatter.get('topics'):
                    topic_name = frontmatter['_topic_name']
                    topic_description = frontmatter['_topic_description']
                    topic, _ = Topic.objects.update_or_create(
                        name=topic_name,
                        defaults={
                            'description': topic_description,
                        }
                    )
                    frontmatter['topics'] = topic
                # 处理标签信息
                if frontmatter.get('tags'):
                    tags = [Tag.objects.get_or_create(name=tag.strip())[0]
                           for tag in frontmatter['tags']]
                    frontmatter['tags'] = tags

                # 创建文章
                article_obj, created = Article.objects.update_or_create(
                    title=frontmatter['title'],
                    slug=str(frontmatter['slug']),
                    defaults={
                        'author': frontmatter['author'],
                        'article_type':frontmatter['article_type'],
                        'image': frontmatter['image'],
                        'category': frontmatter['category'],
                        'topics': frontmatter['topics'],
                        'content': html_content,
                        }

                )
                if 'tags' in frontmatter:
                    article_obj.tags.set(frontmatter['tags'])

                if 'images' in frontmatter:
                    image_paths = frontmatter['images']
                    article_images = [ArticleImage.objects.get_or_create(image=path, article=article_obj)[0]for path in image_paths]
                    article_obj.images.set(article_images)

                self.stdout.write(self.style.SUCCESS(f'成功导入: {md_file.name}'))

            except Exception as e:
                self.stdout.write(self.style.ERROR(f'导入失败 {md_file.name}: {str(e)}'))
    def get_or_create_article_images(self, paths, article_obj):
        images = []
        for path in paths:
            if path:
                image, _ = ArticleImage.objects.get_or_create(image=path, article=article_obj)
                images.append(image)
        return images


    def parse_md_content(self, text):
        # 更健壮的分割frontmatter和内容
        match = re.search(r'^---\s*\n(.*?)\n---\s*\n(.*)', text, re.DOTALL)
        if not match:
            raise ValueError("Invalid Markdown format: Missing frontmatter delimiters")

        front_matter = match.group(1)
        content = match.group(2).strip()

        # 解析YAML元数据
        try:
            data = yaml.safe_load(front_matter)
        except yaml.YAMLError as e:
            raise ValueError(f"YAML解析错误: {str(e)}")

        # 处理作者信息（适配多种格式）
        if 'author' in data:
           author_name=None
           author_email=None
           if isinstance(data['author'], list):
               for item in data['author']:
                   if 'name' in item:
                       author_name = item['name']
                   if 'email' in item:
                       author_email = item['email']
           elif isinstance(data['author'], dict):
               author_name = data['author'].get('name')
               author_email = data['author'].get('email')
           else:
               author_name = data['author']
           data['author_name'] = author_name
           data['author_email'] = author_email
        else:
            data['author_name'] = '匿名用户'
            data['author_email'] = ''

        # 处理分类信息（多层结构）
        if 'category' in data:
            # 获取分类名称（适配数组和字典格式）
            category_name = None
            category_slug = None
            category_description = None
            if isinstance(data['category'], list):
                for item in data['category']:
                    if 'name' in item:
                        category_name = item['name']
                    if 'slug' in item:
                        category_slug = item['slug']
                    if 'description' in item:
                        category_description = item['description']
            elif isinstance(data['category'], dict):
                category_name = data['category'].get('name')
                category_slug = data['category'].get('slug')
                category_description = data['category'].get('description')

            if not category_name:
                category_name = '默认分类'

            data['_category_name'] = category_name  # 用于后续分类创建
            data['_category_slug'] = category_slug or slugify(category_name)
            data['_category_description'] = category_description or ''
        if 'topics' in data:
            # 获取专题名称（适配数组和字典格式）
            topic_name = None
            topic_description = None
            if isinstance(data['topics'], list):
                for item in data['topics']:
                    if 'name' in item:
                        topic_name = item['name']
                    if 'description' in item:
                        topic_description = item['description']
            elif isinstance(data['topics'], dict):
                topic_name = data['topics'].get('name')
                topic_description = data['topics'].get('description')

            if not topic_name:
                topic_name = '默认专题'

            data['_topic_name'] = topic_name  # 用于后续专题创建
            data['_topic_description'] = topic_description or ''
        # 处理日期字段（支持多种格式）
        if 'publish_date' in data:
            try:
                if data['publish_date']:
                    data['publish_date'] = datetime.strptime(
                        data['publish_date'],
                        "%Y-%m-%d %H:%M:%S" if ' ' in data['publish_date'] else "%Y-%m-%d"
                    )
            except (TypeError, ValueError):
                data['publish_date'] = None
        # 处理单图字段
        if 'image' in data:
            data['image'] = data['image'].replace('/media/', '')
        # 处理多图字段
        if 'images' in data:
            data['images'] = [image.replace('/media/', '') for image in data['images']]
        # 处理标签和多图字段（适配多种格式）
        for field in ['tags','images']:
            if field in data:
                # 转换字符串格式为数组
                if isinstance(data[field], str):
                    data[field] = [tag.strip() for tag in data[field].split(',')]
                # 处理字典/列表中的name字段
                elif isinstance(data[field], (list, dict)):
                    processed = []
                    for item in data[field] if isinstance(data[field], list) else [data[field]]:
                        if isinstance(item, dict) and 'name' in item:
                            processed.append(item['name'])
                        elif isinstance(item, str):
                            processed.append(item)
                    data[field] = processed

        # 保留原始内容（Markdown格式）
        data['raw_content'] = content
        return data




